import re

from django.core.mail import send_mail
from django_redis import get_redis_connection
from rest_framework import serializers
from celery_tasks.email.tasks import send_verify_mail
from django.conf import settings
from .models import User



class RegisterCreateSerializer(serializers.ModelSerializer):
    #用户再进行提交的时候有3个数据：校验密码，短信验证码，是否同意协议
    #所以，我们需要定义三个字段                      #allow_blank是否允许为空  allow_null是否允许传入Ｎｏｎｅ
    password2=serializers.CharField(label='密码',allow_null=False,allow_blank=False,write_only=True)
    sms_code=serializers.CharField(label='短信验证码',max_length=6,allow_null=False,allow_blank=False,write_only=True)
    allow=serializers.CharField(label='同意',allow_null=False,allow_blank=False,write_only=True)
    #因为models没有token所以需要自行生成
    token=serializers.CharField(label='token',read_only=True)
    class Meta:
        model=User
        fields=('id','username','password','mobile','password2','sms_code','allow','token','email_active')
        # fields=('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow')
        #因为系统默认的字段　例如密码没有只写，还有USERS最大长度１５０不满足需求添加额外字段，
        extra_kwargs={
            'id':{'read_only':True},
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length':'仅允许5-20个字符的用户',
                    'max_length':'仅允许5-20个字符的用户名'

                }
            },
            'password':{
                'write_only':True,
                'min_length':8,
                'max_length':20,
                'error_messages':{
                   'min_length':'仅允许8-20个字符的密码' ,
                    'max_length': '仅允许8-20个字符的密码',


                }
            }


        }

        def validate_mobile(self, value):
            if not re.match(r'1[3-9]\d{9}', value):
                raise serializers.ValidationError('手机号格式不正确')
            return value

        # def validata_mobile(self,value):
        #     if not re.match(r'1[3-9]\d{9}',value):
        #         raise serializers.ValidationError('格式不对')


        def validate_allow(self, value):
        # 注意，前端提交的是否同意，我们已经转移为字符串
            if value != 'true':
                raise serializers.ValidationError('您未同意协议')
            return value


        # def validate_allow(self,value):
        #     if value!='true':
        #         raise serializers.ValidationError('您未同意协议')
        #     return value
    # 多字端校验，密码是否一直，短信是否一直
        def validate(self, attrs):
        # 比较密码

            password = attrs.get('password')
            password2 = attrs.get('password2')
            # password=attrs['password']
            # password2=attrs['password2']
            if password != password2:
                raise serializers.ValidationError('密码不一致')
            # 比较手机验证码
            # 获取用户提交的验证码
            code = attrs['sms_code']
            # 获取ｒｅｄｉｓ中的验证码
            redis_conn = get_redis_connection('imagecode')
            # 获取手机号码
            mobile = attrs['mobile']
            redis_code = redis_conn.get('sms_%s' % mobile)
            if redis_code is None:
                raise serializers.ValidationError('验证码过期')
            if redis_code.decode() != code:
                raise serializers.ValidationError('验证码不正确')

            return attrs
    #     def validata(self,attrs):
    #         password=attrs.get('password')
    #         password2=attrs.get('password2')
    #         if password!=password2:
    #             raise serializers.ValidationError('两次密码不一致')
    #         code=attrs.get('sms_code')
    #         redis_conn=get_redis_connection('imagecode')
    #         mobile=attrs.get('mobile')
    #         redis_code=redis_conn.get('sms_%s'%mobile)
    #         if redis_code is None:
    #             raise serializers.ValidationError('验证码过期')
    #         if redis_code.decode()!=code:
    #             raise serializers.ValidationError('验证码不正确')



    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['allow']
        del validated_data['sms_code']


        user=super().create(validated_data)
        #把密码转化成加密的形式
        user.set_password(validated_data['password'])
        user.save()
        print('嘻嘻嘻')
        # 补充生成记录登录状态的ｔｏｋｅｎ
        from rest_framework_jwt.settings import api_settings
        #构建一个负荷
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token=token

        return user



class UserDetailSerializer(serializers.ModelSerializer):
    #用户详细信息序列化器
    class Meta:
        model=User
        fields = ('id', 'username',  'mobile', 'email','email_active')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=('id','email')
        extra_kwargs={
            'email':{
                'required':True
            }

        }

    def update(self, instance, validated_data):

        email=validated_data.get('email')
        instance.email=email
        instance.save()
        # 发送激活邮件
        # 生成激活链接
        url = instance.generate_verify_email_url()
        print(url)
        # 发送,注意调用delay方法
        subject = "美多商城邮箱验证"
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, url, url)
        send_mail(subject, "", settings.EMAIL_FROM, [email], html_message=html_message)

        return instance








class UserListSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=['id','username']




